# -*- encoding: utf-8 -*-

"""
------------------------------------------
@File       : class_decorator.py
@Author     : maixiaochai
@Email      : maixiaochai@outlook.com
@CreatedOn  : 2021/8/25 15:16
------------------------------------------
"""
from functools import wraps
from time import time, sleep


def sorted_by_creation(cls):
    """
        用于将实例按照创建时间排序
    """
    original_init = cls.__init__

    @wraps(original_init)
    def new_init(self, *args, **kwargs):
        original_init(self, *args, **kwargs)
        self.createdon = time()

    cls.__init__ = new_init

    cls.__lt__ = lambda self, other: self.createdon < other.createdon
    cls.__gt__ = lambda self, other: self.createdon > other.createdon

    return cls


@sorted_by_creation
class Sortable:
    def __init__(self, identifier):
        self.identifier = identifier

    def __repr__(self):
        return self.identifier


def demo():

    second = Sortable("second")
    sleep(0.1)

    first = Sortable("first")
    sleep(0.1)

    third = Sortable("third")
    sleep(0.1)

    sortable = [first, second, third]
    sortable = sorted(sortable, key=lambda x: x.createdon)

    print(sortable)


if __name__ == '__main__':
    demo()
